const fs = require('fs')
const path = require('path')
const glob = require("glob");
const webpack = require('webpack')
const copyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const createEntry = require("./scripts/createEntry")
const DeletePlugin = require("./scripts/deletePlugin")
const resolve = dir => path.join(__dirname, dir)
const packModules = new Set((process.env.packModules||'home,login').split(','));
const platform = process.env.VUE_APP_PLATFORM
const {publicPath,outputDir} = require('./package.json')
const NODE_ENV = process.env.NODE_ENV
const modules = createModule();
const timeStamp = new Date().getTime();
let realModules = {},_publicPath = publicPath;
function createModule() {
  let entryObj = {};
  glob.sync("./src/modules/**/main.ts").forEach(val => {
    let url = val.split("/")[3];
    //判断要运行的模块
    if(packModules.size > 2 && !packModules.has(url)){
      return false
    }
    entryObj[url] = {
      entry: `src/modules/${url}/main.ts`,
      template: resolve("public/template.html"),
      filename: `${url}/index.html`,
      title: `${url} Page`,
      module: url,
      version: '0.0.1',
      platform: platform,
      publicPath: publicPath,
      env: NODE_ENV
    };
    if(NODE_ENV != 'development'){
      entryObj[url].chunks = [
        'vendors',
        'common',
        url
      ];
    }
  });
  return entryObj;
}
if(platform == 'uniapp'){
  if(NODE_ENV != 'development'){
    _publicPath = "../"
  }
  Object.keys(modules).forEach(key=>{
    let nowModule = modules[key];
    glob.sync(`./src/modules/${nowModule.module}/views/**/index.vue`).forEach(val => {
      const url = val.split("/")[5];
      const realKey = nowModule.module+'/'+url;
      createEntry(resolve(`src/modules/${nowModule.module}/views/${url}`));
      realModules[realKey] = {
        entry: `src/modules/${nowModule.module}/views/${url}/temporaryEntry.ts`,
        template: resolve("public/template.html"),
        filename: `${nowModule.module}/${url}.html`,
        title: `${nowModule.module} Page`,
        module: nowModule.module,
        version: '0.0.1',
        platform: platform,
        publicPath: _publicPath,
        env: NODE_ENV
      };
      if(NODE_ENV != 'development'){
        realModules[realKey].chunks = [
          'vendors',
          'common',
          realKey
        ];
      }
    });
  })
}else{
  realModules = modules;
}

module.exports = {
  pages: realModules,
  publicPath: _publicPath,
  assetsDir: './[name]',
  outputDir: outputDir,
  filenameHashing:false,
  lintOnSave:false,
  //lintOnSave: NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    open: false, // 启动服务后是否打开浏览器
    port: 9004, // 服务端口
    proxy: { // 134  126
      [process.env.VUE_APP_BASE_API]: {
        target: '10.210.10.191:9000',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      }
    }, // 设置代理
    contentBase:'src'
  },
  configureWebpack: config=>{
    if(NODE_ENV != 'development'){
			config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
      config.optimization.splitChunks = {
        chunks: "all",  
        minSize: 1,
        minChunks:1,
        automaticNameDelimiter: '~',
        cacheGroups: {  
          vendors: {
            name: `vendors`,
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            chunks: 'all'
          },
          common: {
            name: `common`,
            test: /src[\\/]components|src[\\/]webServer|src[\\/]styles|src[\\/]utils|src[\\/]libs|src[\\/]other|src[\\/]utils|src[\\/]locales/,
            priority: -15,
            chunks: 'all',
            reuseExistingChunk: true
          }
        }  
      };
    };
    return {
      output: {
        filename: `${platform == 'uniapp'?'':'[name]/'}[name]${platform == 'uniapp'?'/index':''}.js?t=${timeStamp}`,
        chunkFilename: `[name]/[name].js?t=${timeStamp}`
      },
      /**element-plus start*/
      module: {
        rules: [
          {
            test: /\.mjs$/,
            include: /node_modules/,
            type: "javascript/auto"
          },
        ]
      },
      /**element-plus start*/
      plugins:(()=>{
          let plugins = [];
          plugins.push(new HtmlWebpackPlugin(
            {
              title: 'redirect Page',
              template: './redirect.html',
              filename: `index.html`,
              version: '0.0.1',
              plantForm: platform
            }
          ));
          plugins.push(new webpack.DefinePlugin({
            'process.env.VUE_PUBLICPATH': JSON.stringify(_publicPath)
          }))
          if(platform == 'uniapp' && NODE_ENV != 'development'){
            plugins.push(new DeletePlugin(resolve('src'),'temporaryEntry.ts'))
            plugins.push(new DeletePlugin(resolve('src'),'temporaryEntry.vue'))
          }
          return plugins;
      })()
    };
  },
  chainWebpack: (config)=>{
    // config.optimization.delete('splitChunks')
    config.module
      .rule('images')
      .use('url-loader')
      .loader('url-loader')
      .tap(options => {
        // 修改它的选项...
        options.limit = 1;
        options.fallback.options.context = path.resolve(__dirname, 'src/modules');
        options.fallback.options.name = '[path][name].[ext]';
        return options
    });
    config.module
      .rule('svg')
      .use('file-loader')
      .loader('file-loader')
      .tap(options => {
        // 修改它的选项...
        options.limit = 1;
        options.context = path.resolve(__dirname, 'src/modules');
        options.name = '[path][name].[ext]';
        return options
    });
    config.module
      .rule('media')
      .use('url-loader')
      .loader('url-loader')
      .tap(options => {
        // 修改它的选项...
        options.limit = 1;
        options.fallback.options.context = path.resolve(__dirname, 'src/modules');
        options.fallback.options.name = '[path][name].[ext]';
        return options
    });
    config.module
      .rule('fonts')
      .use('url-loader')
      .loader('url-loader')
      .tap(options => {
        // 修改它的选项...
        options.fallback.options.context = path.resolve(__dirname, 'src/modules');
        options.fallback.options.name = '[path][name].[ext]';
        return options
    });
    if(NODE_ENV == 'development'){
      config.plugin('extract-css')
        .use(MiniCssExtractPlugin)//development模式下必须要有这个，否则报错
        .tap(args=>{
          args[0] = args[0] || {}
          args[0].filename = `${platform == 'uniapp'?'':'[name]/'}[name]${platform == 'uniapp'?'/index':''}.css?t=${timeStamp}`;
          args[0].chunkFilename = `[name]/[name].css?t=${timeStamp}`;
          return args;
      });
    }else{
      config.plugin('extract-css')
        .tap(args=>{
          args[0] = args[0] || {}
          args[0].filename = `${platform == 'uniapp'?'':'[name]/'}[name]${platform == 'uniapp'?'/index':''}.css?t=${timeStamp}`;
          args[0].chunkFilename = `[name]/[name].css?t=${timeStamp}`;
          return args;
      });
    }
    
    config.resolve.alias.set('@', path.join(__dirname, 'src/'));
    config.resolve.alias.set('@m', path.join(__dirname, 'src/modules/'));
    config.resolve.alias.set('vue$', 'vue/dist/vue.esm-bundler.js');
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: [
        // 这个是加上自己的路径,不能使用(如下:alias)中配置的别名路径
        path.resolve(__dirname, './src/styles/var.scss')
      ]
    }
  }
};